package com.googlecode.yoohoo.utils;

import java.util.Locale;

import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;

import com.googlecode.yoohoo.config.IConfigManager;
import com.googlecode.yoohoo.message.IMessageManager;

public class AppUtils {
	private static IConfigManager hostConfigManager;
	
	public static String getAppHome(BundleContext bundleContext) {
		return getHostConfigManager(bundleContext).getString(Constants.KEY_APP_HOME);
	}
	
	public static String getConfigHome(BundleContext bundleContext) {
		return getHostConfigManager(bundleContext).getString(Constants.KEY_CONFIG_HOME);
	}
	
	public static IConfigManager getHostConfigManager(BundleContext bundleContext) {
		if (hostConfigManager == null) {
			hostConfigManager = getConfigManager(bundleContext, Constants.HOST_BUNDLE_SYMBOLIC_NAME);
			
			if (hostConfigManager == null)
				throw new IllegalStateException("Host config manager hasn't been registered as a service.");
		}
		
		
		return hostConfigManager;
	}
	
	public static IConfigManager getConfigManager(BundleContext bundleContext) {
		return getConfigManager(bundleContext, OsgiUtils.getSymbolicName(bundleContext.getBundle()));
	}
	
	public static IConfigManager getConfigManager(BundleContext bundleContext, String bundleSymbolicName) {
		try {
			ServiceReference[] serviceRefs = bundleContext.getServiceReferences(IConfigManager.class.getName(),
					FilterCreator.equal(Constants.KEY_BUNDLE_SYMBOLIC_NAME, bundleSymbolicName));
			if (serviceRefs == null || serviceRefs.length == 0)
				return null;
			
			return (IConfigManager)bundleContext.getService(serviceRefs[0]);
		} catch (InvalidSyntaxException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String getHostName(BundleContext bundleContext) {
		return getHostConfigManager(bundleContext).getString(Constants.KEY_HOST_NAME);
	}
	
	public static IMessageManager getMessageManager(BundleContext bundleContext) {
		String filter = FilterCreator.equal(IMessageManager.MESSAGE_MANAGER_BUNDLE_SYMBOLIC_NAME,
				OsgiUtils.getSymbolicName(bundleContext.getBundle()));
		try {
			ServiceReference[] references = bundleContext.getServiceReferences(
					IMessageManager.class.getName(), filter);
			
			if (references != null && references.length > 0) {
				return (IMessageManager)bundleContext.getService(references[0]);
			}
			
			return null;
		} catch (InvalidSyntaxException e) {
			return null;
		}
	}
	
	public static Locale xmlLangToLocale(String xmlLang) {
		if (xmlLang == null || xmlLang.equals(""))
			return Locale.getDefault();
		
		int underlineIndex = xmlLang.indexOf('_');
		if (underlineIndex == -1) {
			return new Locale(xmlLang);
		}
		
		if (underlineIndex == 0 || underlineIndex == xmlLang.length() - 1)
			return Locale.getDefault();
		
		return new Locale(xmlLang.substring(0, underlineIndex),
				xmlLang.substring(underlineIndex + 1, xmlLang.length()));
	}
}
